<?php
defined('BASEPATH') or exit('No direct script access allowed');
/**
 * 微信公众号菜单开发 zhanghang@jimglobal.com
 * time:2019-8-24
 */
define("TOKEN", "xwz");
define('AppKey', 'a3060dd7f245d0e2d8d8720ce18ebc89');

class Wechat extends CI_Controller
{
    public function index()
    {
        if (isset($_GET['echostr'])) { //验证微信
            $this->valid();
        } else {                     //回复消息
            $this->responseMsg();
        }

    }

    public function valid()
    {
        $echoStr = $_GET["echostr"];
        //valid signature , option
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");

        //extract post data
        if (!empty($postStr)) {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $msgType = $postObj->MsgType;
            $event = $postObj->Event;
            $time = time();
            $event = $postObj->Event;
            //自定义图文消息模板
            $imageText = "<xml>
                          <ToUserName><![CDATA[%s]]></ToUserName>
                          <FromUserName><![CDATA[%s]]></FromUserName>
                          <CreateTime>%d</CreateTime>
                          <MsgType><![CDATA[%s]]></MsgType>
                          <ArticleCount>%d</ArticleCount>
                          %s
                        </xml>";

            //判断消息类型
            switch ($msgType) {
                //图文
                case 'text':
                    $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
                    if (!empty($keyword)) {
                        switch ($keyword) {
                            case '时间':
                                $contentStr = "现在是：" . date('Y年m月d日 H时i分s秒');
                                break;
                            case '博客':
                                $contentStr = 'http://www.jhlfs.top/';
                                break;
                            case '520':
                                $meet = strtotime('2015-1-16 00:00:00');
                                $like = strtotime('2017-1-16 00:00:00');
                                $now = time();
                                $m = ceil(($now - $meet) / (3600 * 24));
                                $l = ceil(($now - $like) / (3600 * 24));
                                $contentStr = '君航已经相识第' . $m . '天，相爱第' . $l . '天';
                                break;
                            case '526':
                                $contentStr = '我家小丸子的生日哦~！';
                                break;
                            case 'wifi密码':
                            case 'wifi':
                            case '密码':
                            case 'WiFi':
                                $contentStr = 'Zh49@.526';
                                break;
                            case "pic":
								$picTpl = "<xml>
								<ToUserName><![CDATA[%s]]></ToUserName>
								<FromUserName><![CDATA[%s]]></FromUserName>
								<CreateTime>%s</CreateTime>
								<MsgType><![CDATA[%s]]></MsgType>
								<Image>
								<MediaId><![CDATA[%s]]></MediaId>
								</Image>
								</xml>"; 
								$resultStr = sprintf($picTpl, $fromUsername, $toUsername, $time, 'image', 'hsHpeEbleH6fe1v5B1JiCMUk985aloV-hRrlXrxlXqA');
								echo $resultStr;
								exit; 
                            default:
                                $str = substr($keyword, -6);
                                if ($str == '天气') {
                                    $city = substr($keyword, 0, strlen($keyword) - 6);
                                    $url = 'http://apis.juhe.cn/simpleWeather/query?key=9104855d8571e5fa16e624f4d917b037&city=' . $city;
                                    $data = json_decode(file_get_contents($url), true);
                                    if ($data['error_code'] == 0) {
                                        $contentStr = '';
                                        $flag = ['今天', '明天', '后天'];
                                        $contentStr .= '【' . $data['result']['city'] . '】天气实况' . "\n";
                                        for ($i = 0; $i < 3; $i++) {
                                            $contentStr .= $flag[$i] . '：' . $data['result']['future'][$i]['weather'] . '  温度：' . $data['result']['future'][$i]['temperature'] . '  ' . $data['result']['future'][$i]['direct'] . "\n";
                                        }
                                        $contentStr .= "\n" . '小丸子科技 版权所有';
                                    } else {
                                        $contentStr = '查询出错，你输入的城市名称有误！';
                                    }
                                } else {
                                    $contentStr = '查询城市天气，输入：秦皇岛天气' . "\n";
                                }
                        }

                    } else {
                        echo "Input something...";
                    }

                    break;

                //2事件
                case 'event':
                    $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
                    $msgType = "text";
                    $EventKey = $postObj->EventKey;
                    switch ($event) {
                        case 'subscribe':
                            $contentStr = "欢迎关注张大海官方微信公众号！输入时间、博客和520等关键字，有意外的惊喜哦~";
                            break;
                        case 'CLICK':
                            switch ($EventKey) {
                                case 'joke':
                                    $url = "http://www.kuitao8.com/api/joke";
                                    $cn = curl_init();
                                    curl_setopt($cn, CURLOPT_URL, $url);
                                    curl_setopt($cn, CURLOPT_RETURNTRANSFER, 1);
                                    $b = curl_exec($cn);
                                    curl_close($cn);
                                    $arr = json_decode($b, true);
                                    $contentStr = $arr['content'];
                                    break;
                                case 'loveday':
                                    $meet = strtotime('2015-1-16 00:00:00');
                                    $like = strtotime('2017-1-16 00:00:00');
                                    $now = time();
                                    $m = ceil(($now - $meet) / (3600 * 24));
                                    $l = ceil(($now - $like) / (3600 * 24));
                                    $contentStr = '君航已经相识第' . $m . '天，相爱第' . $l . '天';
                                    break;
                                case 'like':
                                    $contentStr = "感谢您关注我们，我是服务小二，有事您开口～\n\n";
                                    break;
                                case 'today':
                                    $url = 'http://api.juheapi.com/japi/toh?key=' . AppKey . '&v=1.0&month=' . intval(date('m')) . '&day=' . intval(date('d'));
                                    $data = json_decode(file_get_contents($url), true);
                                    $tmp = "%d年%d月%d日  %s";
                                    $contentStr = '';
                                    if ($data['error_code'] == 0) {
                                    	$dataList = array_reverse($data['result']);
                                        foreach ($dataList as $k => $v) {
                                        	if($k < 15){
                                        		$contentStr .= sprintf($tmp, intval($v['year']), intval($v['month']), intval($v['day']), $v['title']) . PHP_EOL;
                                        	}  
                                        }
                                    } else {
                                        $contentStr = '请求错误，请重新尝试！';
                                    }
                                    break;
                                case 'OFFICIALLY_ANNOUNCE':
                                    $articleList = $this->getArtickeTop8();
                                    $item = "<item>
                                              <Title><![CDATA[%s]]></Title>
                                              <Description><![%s]]></Description>
                                              <PicUrl><![CDATA[%s]]></PicUrl>
                                              <Url><![CDATA[%s]]></Url>
                                            </item>";
                                    $str = "<Articles>";
                                    foreach ($articleList as $value) {
                                        $str .= sprintf($item, $value->title, $value->title, $value->thum, $value->url);
                                    }
                                    $str .= "</Articles>";
                                    $msgType = 'news';
                                    $count = count($articleList);
                                    $resultStr = sprintf($imageText, $fromUsername, $toUsername, $time, $msgType, $count, $str);
                                    echo $resultStr;
                                    exit;

                                    break;
                            }

                            break;
                        default:
                    }

                    break;
                default:

            }
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;

        } else {
            echo "";
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    public function menu()
    {
        $get_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . APPID . '&secret=' . APPSECRET;
        $output = Wechat::curl_request($get_token_url);
        $jsoninfo = json_decode($output, true);
        $access_token = $jsoninfo["access_token"];//获取access_token
        //设置微信公众号菜单
        $jsonmenu = '{
      "button":[
      {
            "name":"看科普",
           "sub_button":[
            {
               "type":"view",
                "name":"今日天气",
                "url":"http://m.hao123.com/a/tianqi"
            },
            {
                "type":"view",
                "name":"搜索",
                "url":"http://www.soso.com/"
            },
            {
                "type":"click",
                "name":"历史今天",
                "key":"today"
            }]
       },
       {
           "name":"看文章",
           "sub_button":[
           {
               "type":"view",
                "name":"博客首页",
                "url":"http://www.jhlfs.top/"
            },
            {
               "type":"view",
                "name":"历史文章",
                "url":"http://www.jhlfs.top/history"
            }
            ]
       },
       {
           "name":"找开心",
           "sub_button":[
                {
                    "type":"click",
                    "name":"看笑话",
                    "key":"joke"
                },
                {
                    "type":"click",
                    "name":"相爱天数",
                    "key":"loveday"
                },
                {
                    "type":"click",
                    "name":"君航官宣",
                    "key":"OFFICIALLY_ANNOUNCE"
                },
                {
                   "type":"click",
                   "name":"赞一下我们",
                   "key":"like"
                },{
                    "type":"view",
                    "name":"用户授权",
                    "url":"http://www.wechat.jhlfs.top/wechat/wxAuthentication"
                }
            ]
       }
       ]
 }';
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $access_token;
        $result = Wechat::curl_request($url, $jsonmenu);
        var_dump($result);

    }

    /**
     * curl请求接口
     * @param $url
     * @param null $data
     * @return bool|string
     */
    static function curl_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'ERROR' . curl_error($curl);
        }
        curl_close($curl);
        return $output;
    }

    //获取博客人生感悟文章8篇
    public function getArtickeTop8()
    {
        $http = 'https://www.jhlfs.top';
        $url = 'https://www.jhlfs.top/news/emotion/';
        $dbObj = $this->load->database('default_b3', true);
        $dbObj->where('classify ', 1);
        $dbObj->order_by('id ', 'asc');
        $dbObj->limit(8);
        $list = $dbObj->select('id,title,thum')->get('article')->result();
        foreach ($list as &$item) {
            $item->url = $url . $item->id;
            $item->thum = $http . $item->thum;
        }
        return $list;
    }

    //用户授权认证
    public function wxAuthentication()
    {
        $redirect_uri = urlencode(base_url('wechat/getWechatInfo'));
        //跳转微信回调到redirect_uri获取code
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . APPID . "&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        redirect($url);
    }

    //获取用户信息
    public function getWechatInfo()
    {
        $code = $this->input->get('code');
        if (isset($code)) {
            $userinfo = getWechatUserInfo($code);
            //判断用户是否授权过
            $dbObj = $this->load->database('default_b3', true);
            $dbObj->where('openid ', $userinfo['openid']);
            $result = $dbObj->get('user_wx')->row();
            if (!$result) {
                $param = [
                    'openid'    => $userinfo['openid'],
                    'nickname'  => $userinfo['nickname'],
                    'sex'       => $userinfo['sex'],
                    'address'   => $userinfo['country'] . " " . $userinfo['province'] . " " . $userinfo['city'],
                    'avatarUrl' => saveHeadimgUrl($userinfo['headimgurl'])
                ];
                $dbObj->insert('user_wx', $param);
                $id = $dbObj->insert_id();
                $dbObj->where('id ', $id);
                $result = $dbObj->get('user_wx')->row();
            }
            $result->sex = $result->sex == 1 ? '男' : '女';
            $HTML = "<center>";
            $HTML .= "<h3>USERID：" . $result->openid . "</h3>";
            $HTML .= "<h3>姓名：" . $result->nickname . "</h3>";
            $HTML .= "<h3>性别：" . $result->sex . "</h3>";
            $HTML .= "<h3>地址：" . $result->address . "</h3>";
            $HTML .= "<h3>头像：<img src='" . $result->avatarUrl . "'></h3>";
            $HTML .= "</center>";
            echo $HTML;
        } else {
            echo "NO CODE";
        }

    }


}